import Vue from 'vue'
import Vuex from 'vuex'
import { loginAPI } from '@/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: { // 定制全局状态变量
    token: localStorage.getItem('token') || '',
    refresh_token: localStorage.getItem('refresh_token') || ''
  },
  getters: { // 类似与全局计算属性
  },
  mutations: { // 唯一能同步修改state变量的地方
    SET_TOKEN (state, value) {
      state.token = value
      localStorage.setItem('token', value)
    },
    SET_REFRESH_TOKEN (state, value) {
      state.refresh_token = value
      localStorage.setItem('refresh_token', value)
    }
  },
  actions: { // 异步操作
    async loginActions (store, value) {
      const res = await loginAPI(value)
      store.commit('SET_TOKEN', res.data.data.token)
      store.commit('SET_REFRESH_TOKEN', res.data.data.refresh_token)
      return res // return到逻辑页面当中(async函数始终返回的是一个Promise对象，所以你的结果始终会被当做Promise对象的成功结果返回)
    }
  },
  modules: {
  }
})
